<template>
  <div class="flex flex-col">
    <!-- 子抽屉 -->
    <a-modal
      :title="$t('user.verification-code.required1115661105765')"
      :visible="visible"
      @ok="createAction"
      @cancel="rollback"
      :width="680"
      :ok-text="$t('user.verification-code.required1166')"
      :cancel-text="$t('user.email.required11')"
    >
      <a-form :form="form" labelAlign="right" :forceRender="true">
        <!-- 这个部分是隐藏的数据 -->
        <a-form-item label="ID" class="hidden">
          <a-input v-decorator="['Id']" />
        </a-form-item>
        <a-form-item label="DpiaQid" class="hidden">
          <a-input v-decorator="['DpiaQid']" />
        </a-form-item>
        <!-- 这个部分是隐藏的 -->
        <a-form-item
          style="margin: 0"
          :label="$t('user.verification-code.required1115661105769')"
        >
          <a-input
            v-decorator="[
              'riskName',
              {
                rules: [
                  {
                    required: true,
                    message: $t(
                      'user.verification-code.required111566110577283'
                    ),
                  },
                ],
              },
            ]"
            :placeholder="$t('user.verification-code.required111566110576911')"
            style="width: 615px"
          />
        </a-form-item>
        <a-row>
          <a-col :span="12">
            <a-form-item
              style="margin: 0"
              :label="
                $t('user.verification-code.required111566110576922') + ':'
              "
            >
              <a-input v-decorator="['riskId']" style="width: 300px" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              style="margin: 0"
              :label="$t('user.verification-code.required1115661105770')"
            >
              <a-input
                v-decorator="['riskSource']"
                style="width: 300px"
                disabled
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <!--task Type-->
          <a-col :span="12">
            <a-form-item
              :label="$t('user.verification-code.required1115661105771')"
            >
              <a-select
                v-decorator="[
                  'riskType',
                  {
                    rules: [
                      {
                        required: true,
                        message: $t(
                          'user.verification-code.required111566110577284'
                        ),
                      },
                    ],
                  },
                ]"
                option-filter-prop="children"
                :filter-option="filterOption"
                show-search
                :placeholder="
                  $t('user.login.message-invalid-verification-code0011')
                "
                style="width: 300px"
              >
                <a-select-option
                  v-for="item in statusList"
                  :value="item.value"
                  :key="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :label="$t('user.verification-code.required111566132')"
            >
              <a-date-picker
                v-decorator="[
                  'riskDeadline',
                  {
                    rules: [
                      {
                        type: 'object',
                        required: true,
                        message: this.$t(
                          'user.verification-code.required111566110577285'
                        ),
                      },
                    ],
                  },
                ]"
                format="YYYY-MM-DD"
                style="width: 300px"
                :placeholder="$t('user.verification-code.required111566157')"
                :disabled-date="disabledDate"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <!--owner   任务负责人-->
          <a-col :span="12">
            <a-form-item
              :label="$t('user.verification-code.required1115661105772')"
            >
              <a-select
                v-decorator="[
                  'riskOwnerUserId',
                  {
                    rules: [
                      {
                        required: true,
                        message: $t(
                          'user.verification-code.required111566110577371442281431999'
                        ),
                      },
                    ],
                  },
                ]"
                :placeholder="$t('user.verification-code.required11156612811')"
                show-search
                @search="(...rest) => filte1rOption(...rest, 'userList')"
                :showArrow="false"
                :filterOption="false"
                style="width: 300px"
              >
                <a-select-option
                  v-for="item in userList"
                  :value="item.value"
                  :key="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item style="margin: 0" label="DCO:">
              <a-input
                v-if="dcoType"
                v-decorator="['dco']"
                style="width: 300px"
                disabled
              />
              <a-select
                v-else
                v-decorator="['dco']"
                :placeholder="$t('user.verification-code.required111566130')"
                show-search
                @search="(...rest) => filte1rOption(...rest, 'dcoUserList')"
                :showArrow="false"
                :filterOption="false"
                style="width: 300px"
              >
                <a-select-option
                  v-for="item in dcoUserList"
                  :value="item.value"
                  :key="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <!--等级--> 
          <a-form-item :label="$t('user.verification-code.required111566160')" :colon="false">
            <a-select
              v-decorator="[
                'riskLevel',
                {
                  rules: [
                    {
                      required: true,
                      message: $t(
                        'user.verification-code.required111566110577356'
                      ),
                    },
                  ],
                },
              ]"
              :placeholder="$t('user.verification-code.required11156616011')"
              style="width: 300px"
              option-filter-prop="children"
              :filter-option="filterOption"
              show-search
            >
              <a-select-option
                v-for="item in riskLevel"
                :value="item.value"
                :key="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-row>
        <!--描述--> 
        <a-form-item style="margin: 0;" :label="$t('user.verification-code.required1115661105773')">
          <a-textarea :auto-size="{ minRows: 3, maxRows: 10 }"
                      :placeholder="$t('user.verification-code.required111566110577311')" :rows="3"
                      v-decorator="['riskDetail', { rules: [{ required: true, message: $t('user.verification-code.required111566110577287') }] }]"
                      style="width: 615px;"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>


<script>
import { DcoQuery, getUserList } from "@/api/common/form";
import {
  RISKEditActionList,
  RiskListSelect,
  ristDelActionRemark,
} from "@/api/risk/form";
import { ristCreateActionRemark, ristEditActionRemark } from "@/api/risk/json";
import { dpiaRemarkLists } from "@/api/dpia/form";
import axios from "axios";
import moment from "moment";
import { configurationSelect } from "@/api/configs";
import storage from "store";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { createRisk } from "@/api/dataBreach/form";

export default {
  props: {
    questionId: {
      type: String,
    },
    actionIds: {
      type: Array,
    },
  },
  components: {},
  data() {
    return {
      // 创建DPIA问卷状态
      createQuestionStatus: false,
      // 默认不传ID
      types: false,
      // 下面这些都是通用的
      form: this.$form.createForm(this),
      // 主体状态
      visible: false,
      // 上传文件列表
      fileLists: [],
      // 上传所需的信息
      env: process.env.VUE_APP_BASE_API,
      // 备注列表
      inputList: [],
      // Action的ID
      actionId: "",
      // 用户下拉列表
      userList: [],
      // 时间配置
      config: {
        rules: [
          {
            type: "object",
            required: true,
            message: this.$t("user.verification-code.required111566110577285"),
          },
        ],
      },
      // 状态下拉
      statusList: [],
      // 备注用的信息
      actionCreateUser: "",
      actionCreateUserId: "",
      //触发风险ids
      riskIds: undefined,
      //所选项数据
      actionData: undefined,
      //risk主键ID
      riskIdValue: undefined,
      //risk等级
      riskLevel: [],
      //时间
      timerId: "",
      dcoUserList: [],
      dcoType: true,
      otherData: {},
    };
  },
  methods: {
    async filte1rOption(value, key) {
      const { data } =
        key === "dcoUserList"
          ? await DcoQuery({ ApprovalAlias: "DCO" })
          : await getUserList({ UserEmail: value, UserName: value });
      this[key] = data;
    },
    disabledDate(current) {
      const currentDate = moment().format("YYYY-MM-DD");
      return current && current.format("YYYY-MM-DD") < currentDate;
    },
    async open(allid,id, data, otherData = { version: "v1" }) {
    
      this.riskIds = undefined;
      this.actionData = undefined;
      this.riskIdValue = undefined;
      this.riskIds = id.join();

      this.riskIds = this.riskIds.split(',').map(id => parseInt(id)); 
      this.riskIds = this.riskIds.filter(id => !allid.includes(id));
      this.riskIds = this.riskIds.join(',');
      console.log("我是riskId", this.riskIds);
      
      this.actionData = data;
      this.otherData = otherData;
      // 清空数据
      this.form.resetFields();

      //初始风险等级
      const { data: riskLevel } = await configurationSelect({
        state: 8,
        types: localStorage.getItem("lang").includes("zh-CN") ? 0 : 1,
      });
      this.riskLevel = riskLevel;

      //风险类型
      const { data: riskType } = await configurationSelect({
        state: 9,
        types: localStorage.getItem("lang").includes("zh-CN") ? 0 : 1,
      });
      this.statusList = riskType;
      // 打开弹窗
      this.visible = true;

      // 初始化数据
      this.fileLists = [];
      this.inputList = [];
      await this.$nextTick();
      // if (id == undefined)
      if (id) {
        // 新建走这个
        // 初始化RISK的Action，不带risk的ID
        // const { data } = await RiskListSelect({ DpiaQid: this.questionId });
        let { version, data: paramsData } = otherData;
        const { data: riskId } =
          version === "v1"
            ? await RiskListSelect()
            : version === "v2"
            ? await createRisk({
                breachId: paramsData.breachId,
              })
            : {};
        this.riskIdValue = riskId.value;
        await this.$nextTick();
        this.form.setFieldsValue({
          riskId: riskId.label,
          riskSource:
            data[0][
              version === "v1"
                ? "DpiaActionSource"
                : version === "v2"
                ? "BreachActionSource"
                : ""
            ],
          dco:
            version === "v1"
              ? data[0]?.DpiaActionDcoReview
              : version === "v2"
              ? data[0].BreachActionDcoReview
              : "",
        });
        if (!data[0].DpiaActionDcoReview) {
          this.dcoType = false;
        }
      } else {
        // 编辑走这个
        const { data } = await RISKEditActionList({ Id: id });
        data.DpiaActionFinishTime = data.DpiaActionFinishTime
          ? moment(data.DpiaActionFinishTime, "YYYY-MM-DD HH:mm:ss")
          : null;

        this.form.setFieldsValue(data);
        const { data: remarkLists } = await dpiaRemarkLists({
          ActionId: id,
          ActionType: 1,
        });

        // 保留创建时间、创建人信息
        this.actionCreateUser = data.DpiaActionCreateUser;
        this.actionCreateUserId = data.DpiaActionCreateUserId;

        // 赋值
        this.actionId = data.Id;

        if (remarkLists.length > 0) {
          for (var i = 0; i < remarkLists.length; i++) {
            // 创建备注列表初始化
            this.inputList.push({
              value: remarkLists[i].ActionRemarkInfo,
              editable: false,
              actionCreateTime: remarkLists[i].ActionCreatetime,
              actionCreateUser: remarkLists[i].ActionCreateUserName,
              actionCreateUserId: remarkLists[i].ActionCreateUser,
            });
          }
        }

        this.addInput();
        const { data: fileLists } = await dpiaRemarkLists({
          ActionId: id,
          ActionType: 2,
        });

        if (fileLists.length > 0) {
          for (var i = 0; i < fileLists.length; i++) {
            // 上传的文件处理
            var fileName = fileLists[i].ActionUploadUrl.split("/");
            this.fileLists.push({
              uid: i,
              name: fileName[fileName.length - 1],
              status: "done",
              url: fileLists[i].ActionUploadUrl,
            });
          }
        }
      }
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    createAction() {
      // 执行创建action
      const {
        form: { validateFields },
      } = this;
      // 按钮loading
      this.loading = true;
      // validateFields 是校验form表单数据
      // force: true 是默认所有字段都校验
      // values 表单的值
      validateFields({ force: true }, async (err, values) => {
        if (!err) {
          try {
            for (var i = 0; i < this.userList.length; i++) {
              if (this.userList[i].value == values.riskOwnerUserId) {
                values.riskOwnerUserName = this.userList[i].label;
              }
            }
            for (var i = 0; i < this.userList.length; i++) {
              if (this.userList[i].label == values.dco) {
                values.riskDcoUserId = this.userList[i].value;
              }
            }
            // 时间格式化
            values.riskDeadline = moment(values.riskDeadline).format(
              "YYYY-MM-DD"
            );
            const DpiaQid = this.actionData
              ? this.actionData[0].DpiaQid
              : undefined;
            const params = { ...values };
            values.riskId = this.riskIdValue;
            values.riskState = 3;
            values.riskOwnerUserName = values.riskOwnerUserName.replaceAll(
              "/",
              "#@%$"
            );
            values.riskOwnerUserId = values.riskOwnerUserId.replaceAll(
              "/",
              "#@%$"
            );
            let { version, data: paramsData } = this.otherData;
            if (version === "v1") {
              await RiskListSelect({
                ids: this.riskIds,
                dpiaQid: DpiaQid,
                ...values,
              });
            } else if (version === "v2") {
              await createRisk({
                ids: this.riskIds,
                dpiaQid: DpiaQid,
                breachId: paramsData.breachId,
                riskDcoUserId: values.dco === "-" ? 0 : values.dco,
                riskDcoUserName: this.dcoUserList.filter(
                  (item) => item.value === values.dco
                )[0]?.label,
                ...values,
              });
            }
            this.$emit("succeed");
            this.$emit("getList");
            this.$message.success(
              this.$t("user.verification-code.required111566110577308")
            );
            //如果成功就关闭
            this.rollback();
          } catch (error) {
            console.log("err", error);
            this.$message.error(error);
          } finally {
            this.loading = false;
          }
        } else {
          setTimeout(() => {
            this.loading = false;
          }, 600);
        }
      });
    },
    rollback() {
      // 处理关闭弹窗
      if (this.visible) {
        this.visible = false;
      } else {
        this.visible = true;
      }
    },
    async editInput(item, index) {
      // 打开备注编辑能力
      item.editable = true;
    },
    async deleteInput(item) {
      // 删除备注
      try {
        if (Object.keys(item).indexOf("Id") != -1) {
          // 防止ID被初始化
          if (item.Id != 0) {
            await ristDelActionRemark({ Id: item.Id });
          }
        }
        // 在列表里也删除
        this.inputList.splice(this.inputList.indexOf(item), 1);
      } catch (error) {
        console.log("error:", error);
        this.$message.error(error);
      }
    },
    async okInput(item, index1) {
      // 备注提交信息保存
      item.editable = false;
      if (Object.keys(item).indexOf("Id") != -1) {
        // 更新
        const { data } = await ristEditActionRemark([
          {
            Id: item.Id,
            ActionRemarkInfo: item.value,
            ActionId: this.actionId,
            ActionType: 1,
          },
        ]);
        item.actionCreateTime = data.ActionUpdatetime;
      } else {
        // 新增
        const { data } = await ristCreateActionRemark([
          {
            ActionRemarkInfo: item.value,
            ActionId: this.actionId,
            ActionType: 1,
          },
        ]);
        // 赋值
        item.Id = data.Id;
        item.actionCreateTime = data.ActionCreatetime;
      }
    },
    addInput() {
      // 新增备注
      var objData = new Date();
      var year = objData.getFullYear();
      var month = objData.getMonth() + 1;
      var day = objData.getDate();
      if (objData.getSeconds() < 10) {
        var seconds = "0" + objData.getSeconds();
      } else {
        var seconds = objData.getSeconds();
      }
      if (objData.getMinutes() < 10) {
        var miuntes = "0" + objData.getMinutes();
      } else {
        var miuntes = objData.getMinutes();
      }
      if (objData.getHours() < 10) {
        var hours = "0" + objData.getHours();
      } else {
        var hours = objData.getHours();
      }
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      // 新增一个新的数据初始化
      this.inputList.push({
        value: "",
        editable: true,
        actionCreateTime:
          year +
          "-" +
          month +
          "-" +
          day +
          " " +
          hours +
          ":" +
          miuntes +
          ":" +
          seconds,
        actionCreateUser: this.actionCreateUser,
        actionCreateUserId: this.actionCreateUserId,
      });
    },
    async handleChange(e) {
      // 上传提交
      this.uploadLoading = true;
      let formdata = new FormData();
      formdata.append("file", e.file);
      try {
        const { status, data } = await axios({
          url: `${this.env}/v1/oss/upload`,
          method: "post",
          data: formdata,
          headers: {
            token: storage.get(ACCESS_TOKEN),
            tokens: storage.get("bmwToken") || "",
          },
        });
        if (status == 200 && data.code == 1) {
          if (data.data != "") {
            await this.$nextTick();
            var files = data.data;
            var index = this.fileLists.length;
            if (files != "" && files != undefined) {
              var fileName = files.split("/");
              this.fileLists.push({
                uid: index + 1,
                name: fileName[fileName.length - 1],
                status: "done",
                url: data.data,
              });

              // 上传文件完成后新增
              // 新增
              await ristCreateActionRemark([
                {
                  ActionUploadUrl: data.data,
                  ActionId: this.actionId,
                  ActionType: 2,
                },
              ]);
            }
          }
        } else {
          this.$message.error(
            this.$t("user.verification-code.required111566110577282")
          );
        }
      } catch (error) {
        console.log(error);
        this.$message.error(error);
      } finally {
        this.uploadLoading = false;
      }
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .ant-drawer-body {
  height: 800px !important;
}

.ant-pagination {
  float: right;
}

/deep/ .ant-timeline-item-content {
  top: -11px;
}

/deep/ .ant-timeline-item {
  padding: 0 0 1px;
}

/deep/ .ant-form-item {
  margin-bottom: 0px;
}

/deep/ .ant-space-align-center {
  align-items: center;
  margin-left: 230px;
}

/deep/ .ant-space-align-center {
  align-items: center;
  margin-left: 0 !important;
}
/deep/ .ant-modal-footer {
  padding: 10px 40px !important;
}

</style>